/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package webservices;

import Entities.Resource;
import Entities.User;
import constants.Consts;
import helpers.Debug;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import rhserver.MainController;

/**
 * REST Web Service
 *
 * @author Bari
 */
@Path("getresourcelist")
public class GetResourceList extends AbstractWebService {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of GetResourceList
     */
    public GetResourceList() throws Exception {
        super();
    }

    /**
     * Retrieves representation of an instance of Headertest.GetResourceList
     *
     * @return an instance of java.lang.String
     */
    private List<Resource> getRersourcesJPA(long categoryId, EntityManager em) {


        TypedQuery<Resource> query = em.createNamedQuery("Resource.findByCategoryId", Resource.class);
        query.setParameter("categoryid", categoryId);
        List<Resource> resourceList = query.getResultList();
        return resourceList;

    }

    private JSONObject getResources(long categoryId, User client, EntityManager em) {
        try {
            JSONObject response = new JSONObject();
            List<Resource> resources = getRersourcesJPA(categoryId, em);
            JSONArray jsonArray = new JSONArray();
            for (Resource res : resources) {
                em.refresh(res);// refresh mappedBy fields
                jsonArray.put(res.toJsonWithOwnershipCheck(client));
            }
            response.put(Consts.JSON_ARRAY, jsonArray);
            return response;

        } catch (JSONException ex) {
            Logger.getLogger(GetResourceList.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    @Override
    protected String processJsonMessage(String jsonMessage) {
        EntityManager em = MainController.getInstance().getEntityManager();
        
        try {
            JSONObject receivedJson = new JSONObject(jsonMessage);
            int category = receivedJson.getInt(Consts.RCATEGORY_ID);
            String userAndroidId = receivedJson.getString(Consts.USER_ID);
            User client = getLocalUser(userAndroidId, em);
            Debug.logMessage("GetResourceList", "category id: " + category);
            JSONObject response = getResources(category, client, em);
            Debug.logMessage("processJsonMessage", "message: " + response.toString());
            response.put(Consts.JSON_MESSAGE_CODE, Consts.RESPONSE_RESULT);
            em.close();
            em=null;
            return response.toString();
        } catch (JSONException ex) {
            Logger.getLogger(GetResourceList.class.getName()).log(Level.SEVERE, null, ex);
            em.close();
            em=null;
            return null;
        }

    }
}
